package com.qiangqiang.resoldhouse.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.qiangqiang.resoldhouse.dto.HouseResourceDTO;
import com.qiangqiang.resoldhouse.dto.PageDTO;
import com.qiangqiang.resoldhouse.entity.HouseResource;
import com.qiangqiang.resoldhouse.entity.HouseResourceSelect;
import com.qiangqiang.resoldhouse.enums.HouseEnums;
import com.qiangqiang.resoldhouse.exception.HouseException;
import com.qiangqiang.resoldhouse.mapper.HouseResourceMapper;
import com.qiangqiang.resoldhouse.util.SnowflakeIdWorker;
import com.qiangqiang.resoldhouse.util.TimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: zqh
 * @date: 2018/8/7 16:23
 * @description:
 */
@Service
public class HouseResourceService {

    @Autowired
    HouseResourceMapper mapper;

    public HouseResourceDTO findHouseById(Long houseId) {
        HouseResource houseResource = mapper.selectById(houseId);
        return beanToDTO(houseResource);
    }

    public HouseResourceDTO beanToDTO(HouseResource house){
        if(house == null) return null;
        HouseResourceDTO dto = new HouseResourceDTO();
        BeanUtils.copyProperties(house, dto);
        dto.setCreateTime(TimeFormat.converTime(house.getCreateTime()));
        dto.setUpdateTime(TimeFormat.converTime(house.getUpdateTime()));
        return dto;
    }

    //传进的house为null的字段不会更新到数据库，会使用已有的值，所以createTime不需要设置
    //更新信息后status值为false，需要重新审核
    //更新房源信息
    public Boolean updateHouseResource(HouseResource house){
        house.setUpdateTime(Instant.now().toEpochMilli());
        house.setHouseUnitprice("单价" + Math.round(house.getPrice() * 10000 / house.getHouseArea()) + "元/平米");
        house.setStatus(false);
        mapper.updateById(house);
        return true;
    }

    //添加房源
    public boolean insertHouseResourse(HouseResource houseResource){
        houseResource.setHouseId(new SnowflakeIdWorker(1,1).nextId());
        houseResource.setCreateTime(Instant.now().toEpochMilli());
        houseResource.setUpdateTime(Instant.now().toEpochMilli());
        return mapper.insert(houseResource) > 0;
//        return false;
    }

    //前台发布房源，传进DTO
    public boolean insertHouseResourse(HouseResourceDTO houseDTO, String city){
        HouseResource house = new HouseResource();
        BeanUtils.copyProperties(houseDTO, house);
        house.setStatus(false);
        house.setCity(city);
        house.setHouseUnitprice("单价" + Math.round(houseDTO.getPrice() * 10000 / houseDTO.getHouseArea()) + "元/平米");
        house.setScale(houseDTO.getRoomNum() + "室" + houseDTO.getHallNum() + "厅");
        return insertHouseResourse(house);
    }

    //删除房源by id
    public boolean deleteHouseResourse(Long houseId) {
        HouseResource houseResource = mapper.selectById(houseId);
        if (houseResource == null) {
            throw new HouseException(HouseEnums.House_NOT_EXIST);
        }
        return mapper.deleteById(houseId) > 0;
    }

    //修改房源审核状态
    public boolean passHouse(Long houseId,boolean status){
        HouseResource houseResource = mapper.selectById(houseId);
        houseResource.setUpdateTime(Instant.now().toEpochMilli());
        if (houseResource == null) {
            throw new HouseException(HouseEnums.House_NOT_EXIST);
        }
        if (status){
            houseResource.setStatus(false);
        }
        else{
            houseResource.setStatus(true);
        }
        return  mapper.updateById(houseResource) >0;
    }

    public PageDTO findPage(Integer pageNum){
        return findPage(pageNum, null);
    }


    public PageDTO<HouseResourceDTO> findPage(Integer pageNum, HouseResourceSelect select){
        PageDTO<HouseResourceDTO> pageDTO = new PageDTO<>();
        Page<HouseResourceDTO> page = new Page<>(pageNum, 5);
        List<HouseResourceDTO> result = mapper.selectPage(page, getWrapper(select)).stream()
                .map(this::beanToDTO).collect(Collectors.toList());
        pageDTO.setPage(page);
        pageDTO.setResult(result);
        return pageDTO;
    }

    public Wrapper<HouseResource> getWrapper(HouseResourceSelect select){
        if(select == null) return null;
        Wrapper<HouseResource> wrapper = new EntityWrapper<>();
        boolean first = true, has = false;
        //选城市
        if(select.getCity() != null){
            if(has) wrapper = wrapper.andNew();
            has = true;
            first = true;
            for(String c : select.getCity()) {
                if(first) first = false;
                else wrapper = wrapper.or();
                wrapper = wrapper.eq("city", c);
            }
        }

        //选价格
        if(select.getPrice() != null){
            if(has) wrapper = wrapper.andNew();
            has = true;
            first = true;
            for(String p : select.getPrice()) {
                if(first) first = false;
                else wrapper = wrapper.or();
                String[] num = p.split("-");
                wrapper = wrapper.between("price", num[0], num[1]);
            }
        }

        //选大小
        if(select.getArea() != null){
            if(has) wrapper = wrapper.andNew();
            first = true;
            for(String a : select.getArea()) {
                if(first) first = false;
                else wrapper = wrapper.or();
                String[] num = a.split("-");
                wrapper = wrapper.between("house_area", num[0], num[1]);
            }
        }

        //选状态
        if(select.getStatus() != null){
            if(has) wrapper = wrapper.andNew();
            has = true;
            first = true;
            for(String c : select.getStatus()){
                if(first) first = false;
                else wrapper = wrapper.or();
                wrapper = wrapper.eq("status", c);
            }
        }

        //根据title模糊查询
        if(select.getTitle() != null){
            if(has) wrapper = wrapper.andNew();
            has = true;
            wrapper = wrapper.like("house_name", select.getTitle());
        }

        //根据经纪人查询
        if(select.getAgentId() != null){
            if(has) wrapper = wrapper.andNew();
            has = true;
            wrapper = wrapper.eq("agent_id", select.getAgentId());
        }

        //根据小区查询
        if(select.getEstateName() != null){
            if(has) wrapper = wrapper.andNew();
            has = true;
            wrapper = wrapper.eq("estate_name", select.getEstateName());
        }

        //选择排序方式
        if(select.getOrder() != null && !select.getOrder().equals("default")){
            wrapper.orderBy(select.getOrder());
        }
        return wrapper;
    }

}
